package com.atguigu.crowd.service.impl;

import com.atguigu.crowd.entity.po.MemberConfirmInfoPO;
import com.atguigu.crowd.entity.po.MemberLaunchInfoPO;
import com.atguigu.crowd.entity.po.ProjectPO;
import com.atguigu.crowd.entity.po.ReturnPO;
import com.atguigu.crowd.entity.vo.*;
import com.atguigu.crowd.mapper.*;
import com.atguigu.crowd.service.api.ProjectService;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ProjectServiceImpl implements ProjectService {

    @Autowired
    private ReturnPOMapper returnPOMapper;

    @Autowired
    private MemberConfirmInfoPOMapper memberConfirmInfoPOMapper;

    @Autowired
    private MemberLaunchInfoPOMapper memberLaunchInfoPOMapper;

    @Autowired
    private ProjectPOMapper projectPOMapper;

    @Autowired
    private ProjectItemPicPOMapper projectItemPicPOMapper;




    //获取更多页面的全部项目
    @Override
    @Transactional
    public List<PortalProjectVO> getMoreAll(){
        List<PortalProjectVO> portalProjectVOS = projectPOMapper.selectPortalProjectVOListAll();
        return portalProjectVOS;
    }

    @Override
    public List<PortalProjectVO> getMoreOther(Integer typeId) {
        List<PortalProjectVO> portalProjectVOS = projectPOMapper.selectPortalProjectVOListOther(typeId);
        return portalProjectVOS;
    }

    //申请延期功能
    @Override
    @Transactional()
    public int updateMemberProjectApply(Integer projectId, Integer delayDay, Integer delayNumber) {
        //首先获得改项目的开发周期
        Integer developmentDay1 = projectPOMapper.selectProjectDevelopmentDay(projectId);
        Integer developmentDay = 0;
        developmentDay = developmentDay1+delayDay;
        //将参数与 developmentDay进行放入数据库
        int affectRows = projectPOMapper.updateProjectDelay(projectId, delayDay, delayNumber, developmentDay);
        return affectRows;
    }

    //获取用户发起的项目 即用户关联的项目
    @Override
    public List<DetailProjectVO> getMemberCrowdProjectDeploy(Integer memberId){
        List<DetailProjectVO> projectVOS = projectPOMapper.selectMemberDetailProjectVO(memberId);
        for (DetailProjectVO p: projectVOS) {
            System.out.println("开发周期 p :"+p.getDevelopmentDay());
            //2.根据 status 确定 statusText
            //-1 审核中
            //0-众筹中，1-阶段1，2-阶段2，3-阶段3  4-阶段4
            //5-众筹成功 6-众筹失败 7-项目成功 8-项目失败
            Integer status = p.getStatus();
            switch (status) {
                case -2:
                    p.setStatusText("审核失败");
                    break;
                case -1:
                    p.setStatusText("审核中");
                    break;
                case 0:
                    p.setStatusText("众筹中");
                    break;
                case 1:
                    p.setStatusText("阶段1");
                    break;
                case 2:
                    p.setStatusText("阶段2");
                    break;
                case 3:
                    p.setStatusText("阶段3");
                    break;
                case 4:
                    p.setStatusText("阶段4");
                    break;
                case 5:
                    p.setStatusText("众筹成功");
                    break;
                case 6:
                    p.setStatusText("众筹失败");
                    break;
                case 7:
                    p.setStatusText("项目成功");
                    break;
                case 8:
                    p.setStatusText("项目失败");
                    break;
                default:
                    break;
            }
            // 3.根据deployeDate计算lastDay 这里暂时没有与后端交互 则没有审核通过的日期
            //则设审核通过日期为2020-10-15
            // 2020-10-15
//            p.setDeployDate("0000-00-00");
//            System.out.println("状态码："+p.getStatus());
            if (p.getStatus()==0){
                String deployDate = p.getDeployDate();

                // 获取当前日期
                Date currentDay = new Date();

                // 把众筹日期解析成Date类型
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date deployDay = format.parse(deployDate);

                    // 获取当前当前日期的时间戳
                    long currentTimeStamp = currentDay.getTime();

                    // 获取众筹日期的时间戳
                    long deployTimeStamp = deployDay.getTime();

                    // 两个时间戳相减计算当前已经过去的时间
                    long pastDays = (currentTimeStamp - deployTimeStamp) / 1000 / 60 / 60 / 24;

                    // 获取总的众筹天数
                    Integer totalDays = p.getDay();

                    // 使用总的众筹天数减去已经过去的天数得到剩余天数
                    Integer lastDay = (int) (totalDays - pastDays);

                    p.setLastDay(lastDay);

                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }else if(p.getStatus()==-1){
                //审核中
                p.setLastDay(0);
            }
        }

        return projectVOS;
    }




    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    @Override
    public void saveProject(ProjectVO projectVO, Integer memberId) {

        // 一、保存ProjectPO对象
        // 1.创建空的ProjectPO对象
        ProjectPO projectPO = new ProjectPO();

        // 2.把projectVO中的属性复制到projectPO中
        BeanUtils.copyProperties(projectVO, projectPO);

        // 修复bug：把memberId设置到projectPO中
        projectPO.setMemberid(memberId);

        // 修复bug：生成创建时间存入
        String createdate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        projectPO.setCreatedate(createdate);

        System.out.println("deployDate "+projectPO.getDeploydate());


        // 修复bug：status设置成-1，表示进入审核
        projectPO.setStatus(-1);

        // 3.保存projectPO
        // 为了能够获取到projectPO保存后的自增主键，需要到ProjectPOMapper.xml文件中进行相关设置
        // <insert id="insertSelective" useGeneratedKeys="true" keyProperty="id" ……
        projectPOMapper.insertSelective(projectPO);

        // 4.从projectPO对象这里获取自增主键
        Integer projectId = projectPO.getId();
        // System.out.println("projectId "+projectId);

        // 二、保存项目、分类的关联关系信息
        // 1.从ProjectVO对象中获取typeIdList
        List<Integer> typeIdList = projectVO.getTypeIdList();
        projectPOMapper.insertTypeRelationship(typeIdList, projectId);

        // 三、保存项目、标签的关联关系信息
        List<Integer> tagIdList = projectVO.getTagIdList();

        projectPOMapper.insertTagRelationship(tagIdList, projectId);

        // 四、保存项目中详情图片路径信息
        List<String> detailPicturePathList = projectVO.getDetailPicturePathList();
        projectItemPicPOMapper.insertPathList(projectId, detailPicturePathList);

        // 五、保存项目发起人信息
        MemberLauchInfoVO memberLauchInfoVO = projectVO.getMemberLauchInfoVO();
        MemberLaunchInfoPO memberLaunchInfoPO = new MemberLaunchInfoPO();
        BeanUtils.copyProperties(memberLauchInfoVO, memberLaunchInfoPO);
        memberLaunchInfoPO.setMemberid(memberId);


        //这里再次调用看是否已经有发起人
        int count = memberLaunchInfoPOMapper.selectByMemberId(memberId);
        System.out.println("填写的发起人信息："+memberLaunchInfoPO);
        System.out.println("发起人:"+count);

        if (count>=1){
           //已经有发起人信息 则更新
            //获取已经存在的发起人id
            int id = memberLaunchInfoPOMapper.selectIdByMemberId(memberId);
            memberLaunchInfoPO.setId(id);
            memberLaunchInfoPOMapper.updateByPrimaryKey(memberLaunchInfoPO);
        }else {
            //没有 则插入
            memberLaunchInfoPOMapper.insertSelective(memberLaunchInfoPO);
        }


        // 六、保存项目回报信息
        List<ReturnVO> returnVOList = projectVO.getReturnVOList();

        List<ReturnPO> returnPOList = new ArrayList<>();

        for (ReturnVO returnVO : returnVOList) {

            ReturnPO returnPO = new ReturnPO();

            BeanUtils.copyProperties(returnVO, returnPO);

            returnPOList.add(returnPO);
        }

        returnPOMapper.insertReturnPOBatch(returnPOList, projectId);

        // 七、保存项目确认信息
        MemberConfirmInfoVO memberConfirmInfoVO = projectVO.getMemberConfirmInfoVO();
        MemberConfirmInfoPO memberConfirmInfoPO = new MemberConfirmInfoPO();
        BeanUtils.copyProperties(memberConfirmInfoVO, memberConfirmInfoPO);
        memberConfirmInfoPO.setMemberid(memberId);
        memberConfirmInfoPOMapper.insert(memberConfirmInfoPO);
        System.out.println("开发周期："+projectPO.getDevelopment_day());

    }

    //查询PortalTypeVOList
    @Override
    public List<PortalTypeVO> getPortalTypeVO() {
        return projectPOMapper.selectPortalTypeVOList();
    }

    //根据项目ID查询出项目详细信息  其中包括回报信息列表  详情图片列表
    //填充DetailProjectVO的一些数据
    @Override
    public DetailProjectVO getDetailProjectVO(Integer projectId) {

        DetailProjectVO detailProjectVO = projectPOMapper.selectDetailProjectVO(projectId);
        Integer percentage = detailProjectVO.getPercentage();



        //2.根据 status 确定 statusText
        Integer status = detailProjectVO.getStatus();
        switch (status) {
            case -2:
                detailProjectVO.setStatusText("审核失败");
                break;
            case -1:
                detailProjectVO.setStatusText("审核中");
                break;
            case 0:
                detailProjectVO.setStatusText("众筹中");
            break;
            case 1:
                detailProjectVO.setStatusText("阶段1");
            break;
            case 2:
                detailProjectVO.setStatusText("阶段2");
            break;
            case 3:
                detailProjectVO.setStatusText("阶段3");
                break;
            case 4:
                detailProjectVO.setStatusText("阶段4");
                break;
            case 5:
                detailProjectVO.setStatusText("众筹成功");
                break;
            case 6:
                detailProjectVO.setStatusText("众筹失败");
                break;
            case 7:
                detailProjectVO.setStatusText("项目成功");
                break;
            case 8:
                detailProjectVO.setStatusText("项目失败");
                break;
            default:
                break;
        }
        // 3.根据deployeDate计算lastDay 这里暂时没有与后端交互 则没有审核通过的日期
        //则设审核通过日期为2020-10-15
        // 2020-10-15
        //已经到详情信息页 则已经审核了
        String deployDate = detailProjectVO.getDeployDate();
        System.out.println("详情信息页的项目开始众筹日期："+deployDate);
//        if(deployDate == ""){
//            //还没有审核
//            detailProjectVO.setDeployDate("0000-00-00");
//        }

        // 获取当前日期
        Date currentDay = new Date();

        // 把众筹日期解析成Date类型
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date deployDay = format.parse(deployDate);

            // 获取当前当前日期的时间戳
            long currentTimeStamp = currentDay.getTime();

            // 获取众筹日期的时间戳
            long deployTimeStamp = deployDay.getTime();

            // 两个时间戳相减计算当前已经过去的时间
            long pastDays = (currentTimeStamp - deployTimeStamp) / 1000 / 60 / 60 / 24;

            // 获取总的众筹天数
            Integer totalDays = detailProjectVO.getDay();

            // 使用总的众筹天数减去已经过去的天数得到剩余天数
            Integer lastDay = (int) (totalDays - pastDays);
//            if(lastDay<0&&percentage<100){
//                //众筹失败
//            }else if(lastDay>=0&&percentage>=100){
//                //众筹成功
//            }

            detailProjectVO.setLastDay(lastDay);

        } catch (ParseException e) {
            e.printStackTrace();
        }

        return detailProjectVO;
    }
}
